package com.uinnova.product.eam.service.asset.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.binary.core.lang.StringUtils;
import com.binary.core.util.BinaryUtils;
import com.binary.framework.exception.ServiceException;
import com.binary.jdbc.Page;
import com.google.common.collect.Lists;
import com.uinnova.product.eam.comm.exception.BusinessException;
import com.uinnova.product.eam.comm.model.es.CEamAttention;
import com.uinnova.product.eam.comm.model.es.EamAttention;
import com.uinnova.product.eam.comm.model.es.EamCategory;
import com.uinnova.product.eam.config.Env;
import com.uinnova.product.eam.model.cj.domain.PlanDesignInstance;
import com.uinnova.product.eam.model.constants.DiagramConstant;
import com.uinnova.product.eam.model.dto.AttentionDto;
import com.uinnova.product.eam.model.vo.AttentionVo;
import com.uinnova.product.eam.model.vo.CiDirVo;
import com.uinnova.product.eam.model.vo.EamCategoryVO;
import com.uinnova.product.eam.service.EamCategorySvc;
import com.uinnova.product.eam.service.asset.IAttentionSvc;
import com.uinnova.product.eam.service.cj.service.PlanDesignInstanceService;
import com.uinnova.product.eam.service.es.IamsEsAttentionDao;
import com.uinnova.product.vmdb.comm.i18n.MessageUtil;
import com.uinnova.product.vmdb.comm.model.ci.CCcCi;
import com.uinnova.product.vmdb.comm.model.ci.CCcCiClass;
import com.uinnova.product.vmdb.provider.ci.bean.CcCiClassInfo;
import com.uinnova.product.vmdb.provider.ci.bean.CcCiInfo;
import com.uinnova.product.vmdb.provider.ci.bean.CiGroupPage;
import com.uinnova.project.api.diagram.v2.client.ESDiagramApiClient;
import com.uinnova.project.base.diagram.comm.model.ESDiagram;
import com.uino.api.client.cmdb.ICIApiSvc;
import com.uino.api.client.cmdb.ICIClassApiSvc;
import com.uino.api.client.permission.IUserApiSvc;
import com.uino.bean.cmdb.base.LibType;
import com.uino.bean.cmdb.query.ESCISearchBean;
import com.uino.bean.permission.business.UserInfo;
import com.uino.bean.permission.query.CSysUser;
import com.uino.util.sys.SysUtil;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Service
public class AttentionSvcImpl implements IAttentionSvc {

    @Autowired
    private IamsEsAttentionDao iamsEsAttentionDao;
    @Resource
    private ESDiagramApiClient diagramApiClient;
    @Resource
    private EamCategorySvc categorySvc;

    @Autowired
    private ICIApiSvc iciApiSvc;

    @Autowired
    private IUserApiSvc userApiSvc;

    @Value("${http.resource.space}")
    private String httpResouceUrl;

    @Autowired
    private ICIClassApiSvc iciClassApiSvc;

    @Autowired
    private PlanDesignInstanceService planDesignInstanceService;

    private static final String USERID = "userId";

    private static final String MODIFY_TIME = "modifyTime";

    @Override
    public Long saveOrUpdateAttention(EamAttention eamAttention) {
        try {
            BoolQueryBuilder builder = QueryBuilders.boolQuery();
            builder.must(QueryBuilders.termQuery("attentionId", eamAttention.getAttentionId()));
            builder.must(QueryBuilders.termQuery(USERID, eamAttention.getUserId()));
            List<EamAttention> checkList = iamsEsAttentionDao.getListByQuery(builder);
            if(!CollectionUtils.isEmpty(checkList)){
                return checkList.get(0).getId();
            }
            eamAttention.setCreateTime(BinaryUtils.getNumberDateTime());
            eamAttention.setModifyTime(BinaryUtils.getNumberDateTime());
            return iamsEsAttentionDao.saveOrUpdate(eamAttention);
        } catch (Exception e) {
            throw new ServiceException("新增我的关注错误!", e);
        }
    }

    @Override
    public AttentionVo findAttentionList(Integer pageNum, Integer pageSize, AttentionDto attentionDto) {
        // 校验参数
        MessageUtil.checkEmpty(attentionDto, "eamAttention");
//        MessageUtil.checkEmpty(attentionDto.getAttentionBuild(), "attentionBuild");
        MessageUtil.checkEmpty(attentionDto.getUserId(), USERID);
        // 封装查询条件
        BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
//        queryBuilder.must(QueryBuilders.termQuery("attentionBuild", attentionDto.getAttentionBuild()));
        queryBuilder.must(QueryBuilders.termQuery(USERID, attentionDto.getUserId()));

        AttentionVo attentionVo = new AttentionVo();
        // 企业级架构资产或系统级架构资产文件夹列表
        List<EamCategoryVO> eamDiagramDirList = new ArrayList<>();
        // 视图列表
        List<ESDiagram> diagramList = new ArrayList<>();
        // 系统文件夹详情
        List<CiGroupPage> pageList = new ArrayList<>();
        // 获取分页数据
        List<SortBuilder<?>> sorts = new ArrayList<>();
        //暂时先去掉，只按照关注时间排序
        //sorts.add(SortBuilders.fieldSort("attentionType").order(SortOrder.ASC));
        sorts.add(SortBuilders.fieldSort(MODIFY_TIME).order(SortOrder.DESC));
        Page<EamAttention> eamAttentionPage = iamsEsAttentionDao.getSortListByQuery(pageNum, pageSize, queryBuilder, sorts);
        List<EamAttention> data = eamAttentionPage.getData();
        if(CollectionUtils.isEmpty(data)){
            attentionVo.setAssetsDirList(eamDiagramDirList);
            attentionVo.setDiagramList(diagramList);
            attentionVo.setCiGroupPage(pageList);
            return attentionVo;
        }
        List<Long> attentionIds = data.stream().map(EamAttention::getAttentionId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
        List<EamCategory> attentionDirList = categorySvc.getByIds(attentionIds, LibType.DESIGN);
        Map<Long, EamCategory> attentionDirMap = attentionDirList.stream().collect(Collectors.toMap(EamCategory::getId, each -> each, (k1, k2) -> k2));
        for(EamAttention attention : data) {
            if (attention.getAttentionType() == 1) {
//                EamDiagramDir diagramDir = diagramDirSvc.findDiagramDirById(attention.getAttentionId());
                EamCategory diagramDir = attentionDirMap.get(attention.getAttentionId());
                if (diagramDir != null) {
                    if (!StringUtils.isEmpty(attentionDto.getLike()) && !diagramDir.getDirName().contains(attentionDto.getLike())) {
                        continue;
                    }
//                    EamDiagramDirVo eamDiagramDirVo = new EamDiagramDirVo();
                    EamCategoryVO eamDiagramDirVo = new EamCategoryVO();
                    BeanUtils.copyProperties(diagramDir, eamDiagramDirVo);
                    // 系统文件夹添加系统详情
                    CiGroupPage ciGroupPage = null;
                    if (eamDiagramDirVo.getCiCode() != null && "1".equals(eamDiagramDirVo.getCiCode())) {
                        ESCISearchBean bean = new ESCISearchBean();
                        CCcCi cdt = new CCcCi();
                        cdt.setCiCode(eamDiagramDirVo.getCiCode());
                        bean.setCdt(cdt);
                        ciGroupPage = iciApiSvc.queryPageBySearchBean(bean, false);
                        CcCiInfo ccCiInfo = ciGroupPage.getData().get(0);
                        Map<String, String> attrs = ccCiInfo.getAttrs();
                        String contact = attrs.get("业务联系人及部门");
                        if (contact!=null && contact.startsWith("[") && contact.endsWith("]")) {
                            List<String> list = JSON.parseArray(contact, String.class);
                            StringJoiner stringJoiner = new StringJoiner(", ");
                            list.forEach(stringJoiner::add);
                            attrs.put("业务联系人及部门", stringJoiner.toString());
                        }
                        pageList.add(ciGroupPage);
                    }
                    UserInfo userInfo = userApiSvc.getUserInfoByLoginCode(diagramDir.getOwnerCode());
                    if (userInfo != null) {
                        eamDiagramDirVo.setUserName(userInfo.getUserName());
                    } else {
                        eamDiagramDirVo.setUserName("admin");
                    }
                    eamDiagramDirVo.setIsAttention(DiagramConstant.IS_ATTENTION);
                    eamDiagramDirList.add(eamDiagramDirVo);
                } else {
                    iamsEsAttentionDao.deleteById(attention.getId());
                }
            } else if (attention.getAttentionType() == 2) {
                ESDiagram esDiagram = diagramApiClient.querySimpleDiagramInfoById(attention.getAttentionId());
                if (!BinaryUtils.isEmpty(esDiagram)) {
                    ESDiagram diagram = new ESDiagram();
                    if (!StringUtils.isEmpty(attentionDto.getLike()) && !diagram.getName().contains(attentionDto.getLike())) {
                        continue;
                    }
                    Long dirId = diagram.getDirId();
                    EamCategory diagramDir = attentionDirMap.get(dirId);
                    if (diagramDir != null && !StringUtils.isEmpty(diagramDir.getDirName())) {
                        diagram.setRelationLocation(diagramDir.getDirName());
                    }
                    diagram.setIsAttention(DiagramConstant.IS_ATTENTION);
                    diagramList.add(diagram);
                } else {
                    iamsEsAttentionDao.deleteById(attention.getId());
                }
            }
        }
        attentionVo.setAssetsDirList(eamDiagramDirList);
        attentionVo.setDiagramList(diagramList);
        attentionVo.setCiGroupPage(pageList);

        // 封装分页信息
        Map<String, Long> pageMap = this.transResult(pageNum, pageSize, eamAttentionPage);
        attentionVo.setPageMap(pageMap);
        attentionVo.setAttentionList(data);
        return attentionVo;
    }

    @Override
    public AttentionVo findAttentionList(Integer pageNum, Integer pageSize, Long userId) {
        // 校验参数
        MessageUtil.checkEmpty(userId, USERID);
        // 封装查询条件
        BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
        queryBuilder.must(QueryBuilders.termQuery(USERID, userId));

        AttentionVo attentionVo = new AttentionVo();
        // 企业级架构资产或系统级架构资产文件夹列表
        List<EamCategoryVO> eamDiagramDirList = new ArrayList<>();
        // 视图列表
        List<ESDiagram> diagramList = new ArrayList<>();
        //方案列表
        List<PlanDesignInstance> planDesignList = new ArrayList<>();
        //创建人
        Map<String, UserInfo> userInfoMap = new ConcurrentHashMap<>();
        // 系统文件夹详情
        List<CiGroupPage> pageList = new ArrayList<>();
        // 获取分页数据
        List<SortBuilder<?>> sorts = new ArrayList<>();
        //暂时先去掉，只按照关注时间排序
        sorts.add(SortBuilders.fieldSort(MODIFY_TIME).order(SortOrder.DESC));
        Page<EamAttention> eamAttentionPage = iamsEsAttentionDao.getSortListByQuery(pageNum, pageSize, queryBuilder, sorts);
        List<EamAttention> data = eamAttentionPage.getData();
        attentionVo.setAttentionList(data);
        if(CollectionUtils.isEmpty(data)){
            attentionVo.setAssetsDirList(eamDiagramDirList);
            attentionVo.setDiagramList(diagramList);
            attentionVo.setPlanDesignList(planDesignList);
            attentionVo.setUserInfoMap(userInfoMap);
            attentionVo.setCiGroupPage(pageList);
            return attentionVo;
        }
        // 区分设计空间及资产仓库
        Map<Integer, List<EamAttention>> sourceGroup = data.stream().collect(Collectors.groupingBy(EamAttention::getSource));
        List<Long> privateId = Collections.emptyList();
        if (!CollectionUtils.isEmpty(sourceGroup.get(0))) {
            privateId = sourceGroup.get(0).stream().map(EamAttention::getAttentionId).collect(Collectors.toList());
        }
        List<Long> designId = Collections.emptyList();
        if (!CollectionUtils.isEmpty(sourceGroup.get(1))) {
           designId = sourceGroup.get(1).stream().map(EamAttention::getAttentionId).collect(Collectors.toList());
        }


        Map<Integer, List<EamAttention>> attentionMap = data.stream().filter(attention -> attention.getAttentionId() != null).collect(Collectors.groupingBy(EamAttention::getAttentionType));
        //创建人
        Set<String> loginCodes = new HashSet<>();
        Set<Long> attentionDirIds = new HashSet<>();
        HashSet<Long> attentionPrivateDirIds = new HashSet<>();
        //查视图
        Map<Long, ESDiagram> attentionDiagramMap = new ConcurrentHashMap<>();
        if (attentionMap.containsKey(2)) {
            List<Long> attentionDiagramIds = attentionMap.get(2).stream().map(EamAttention::getAttentionId).distinct().collect(Collectors.toList());
            BoolQueryBuilder diagramQuery = QueryBuilders.boolQuery();
            diagramQuery.must(QueryBuilders.termsQuery("id", attentionDiagramIds));
            diagramQuery.must(QueryBuilders.termQuery("status", 1));
            diagramQuery.must(QueryBuilders.termQuery("domainId", SysUtil.getCurrentUserInfo().getDomainId()));
            Page<ESDiagram> diagramPage = diagramApiClient.selectListByQuery(1, 3000, diagramQuery);
            if (!CollectionUtils.isEmpty(diagramPage.getData())) {
                loginCodes.addAll(diagramPage.getData().stream().map(ESDiagram::getCreator).collect(Collectors.toSet()));
                attentionDiagramMap = diagramPage.getData().stream().collect(Collectors.toMap(ESDiagram::getId, e -> e));
                for (ESDiagram diagram : diagramPage.getData()) {
                    if (privateId.contains(diagram.getId())) {
                        attentionPrivateDirIds.add(diagram.getDirId());
                    } else if (designId.contains(diagram.getId())) {
                        attentionDirIds.add(diagram.getDirId());
                    }
                }
//                attentionDirIds.addAll(diagramPage.getData().stream().map(ESDiagram::getDirId).collect(Collectors.toSet()));
            }
        }
        //查方案
        Map<Long, PlanDesignInstance> attentionPlanMap = new ConcurrentHashMap<>();
        if (attentionMap.containsKey(3)) {
            List<Long> attentionPlanIds = attentionMap.get(3).stream().map(EamAttention::getAttentionId).distinct().collect(Collectors.toList());
            List<PlanDesignInstance> plans = planDesignInstanceService.getByIds(attentionPlanIds);
            if (!CollectionUtils.isEmpty(plans)) {
                loginCodes.addAll(plans.stream().map(PlanDesignInstance::getCreatorCode).collect(Collectors.toSet()));
                attentionPlanMap = plans.stream().collect(Collectors.toMap(PlanDesignInstance::getId, e -> e));
                for (PlanDesignInstance plan : plans) {
                    if (privateId.contains(plan.getId())) {
                        attentionPrivateDirIds.add(plan.getDirId());
                    } else if (designId.contains(plan.getId())) {
                        attentionDirIds.add(plan.getDirId());
                    }
                }
//                attentionDirIds.addAll(plans.stream().map(PlanDesignInstance::getDirId).collect(Collectors.toSet()));
            }
        }
        //查目录
        Map<Long, EamCategory> dirMap = new ConcurrentHashMap<>();
        Map<Long, EamCategory> dirPrivateMap = new ConcurrentHashMap<>();
        if (!CollectionUtils.isEmpty(attentionDirIds) || !CollectionUtils.isEmpty(attentionPrivateDirIds)) {
            List<EamCategory> dirList = categorySvc.getByIds(new ArrayList<>(attentionDirIds), LibType.DESIGN);
            if (!CollectionUtils.isEmpty(dirList)) {
                dirMap = dirList.stream().collect(Collectors.toMap(EamCategory::getId, each -> each, (k1, k2) -> k2));
            }
        }
        if (!CollectionUtils.isEmpty(attentionPrivateDirIds)) {
            List<EamCategory> dirPrviteList = categorySvc.getByIds(new ArrayList<>(attentionPrivateDirIds), LibType.PRIVATE);
            if (!CollectionUtils.isEmpty(dirPrviteList)) {
                dirPrivateMap = dirPrviteList.stream().collect(Collectors.toMap(EamCategory::getId, each -> each, (k1, k2) -> k2));
            }
        }
        //查创建人信息
        if (!CollectionUtils.isEmpty(loginCodes)) {
            CSysUser cdt = new CSysUser();
            cdt.setLoginCodes(loginCodes.toArray(new String[loginCodes.size()]));
            List<UserInfo> userInfos = userApiSvc.getUserInfoByCdt(cdt, true);
            if (!CollectionUtils.isEmpty(userInfos)) {
                userInfoMap = userInfos.stream().collect(Collectors.toMap(UserInfo::getLoginCode, e -> e));
            }
        }
        this.fillAttentionInfo(data, attentionDiagramMap, dirMap, dirPrivateMap, diagramList, attentionPlanMap, planDesignList);
        attentionVo.setAssetsDirList(eamDiagramDirList);
        attentionVo.setDiagramList(diagramList);
        attentionVo.setPlanDesignList(planDesignList);
        attentionVo.setUserInfoMap(userInfoMap);
        attentionVo.setCiGroupPage(pageList);

        // 封装分页信息
        Map<String, Long> pageMap = this.transResult(pageNum, pageSize, eamAttentionPage);
        attentionVo.setPageMap(pageMap);
        return attentionVo;
    }

    private void fillAttentionInfo(List<EamAttention> data, Map<Long, ESDiagram> attentionDiagramMap
            , Map<Long, EamCategory> dirMap, Map<Long, EamCategory> dirPrivateMap, List<ESDiagram> diagramList
            , Map<Long, PlanDesignInstance> attentionPlanMap, List<PlanDesignInstance> planDesignList) {
        for(EamAttention attention : data) {
            if (attention.getAttentionType() == 2) {
                ESDiagram diagram = attentionDiagramMap.get(attention.getAttentionId());
                if (diagram == null) {
                    iamsEsAttentionDao.deleteById(attention.getId());
                    continue;
                }
                Long dirId = diagram.getDirId();
                if (attention.getSource().equals(0)) {
                    EamCategory diagramDir = dirPrivateMap.get(dirId);
                    if (diagramDir != null && !StringUtils.isEmpty(diagramDir.getDirName())) {
                        diagram.setRelationLocation(diagramDir.getDirName());
                    }
                } else {
                    EamCategory diagramDir = dirMap.get(dirId);
                    if (diagramDir != null && !StringUtils.isEmpty(diagramDir.getDirName())) {
                        diagram.setRelationLocation(diagramDir.getDirName());
                    }
                }
                diagram.setIsAttention(DiagramConstant.IS_ATTENTION);
                diagramList.add(diagram);
            } else if (attention.getAttentionType() == 3) {
                PlanDesignInstance plan = attentionPlanMap.get(attention.getAttentionId());
                if (plan == null) {
                    iamsEsAttentionDao.deleteById(attention.getId());
                    continue;
                }
                planDesignList.add(plan);
            }
        }
    }

    @Override
    public Integer cancelAttention(EamAttention eamAttention) {
        MessageUtil.checkEmpty(eamAttention, "eamAttention");
        MessageUtil.checkEmpty(eamAttention.getAttentionId(), "attentionId");
        //MessageUtil.checkEmpty(eamAttention.getAttentionBuild(), "attentionBuild");
        MessageUtil.checkEmpty(eamAttention.getAttentionType(), "attentionType");
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        builder.must(QueryBuilders.termQuery("attentionId", eamAttention.getAttentionId()));
        //builder.must(QueryBuilders.termQuery("attentionBuild", eamAttention.getAttentionBuild()));
        builder.must(QueryBuilders.termQuery("attentionType", eamAttention.getAttentionType()));
        if (eamAttention.getUserId() != null) {
            builder.must(QueryBuilders.termQuery(USERID, eamAttention.getUserId()));
        }
        return iamsEsAttentionDao.deleteByQuery(builder, true);
    }

    @Override
    public void cancelAttentionBatch(List<Long> attentionIds, Integer attentionType) {
        MessageUtil.checkEmpty(attentionIds, "attentionIds");
        MessageUtil.checkEmpty(attentionType, "attentionType");
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        builder.must(QueryBuilders.termsQuery("attentionId", attentionIds));
        builder.must(QueryBuilders.termQuery("attentionType", attentionType));
        iamsEsAttentionDao.deleteByQuery(builder, true);
    }

    @Override
    public List<EamAttention> findUserAttentionList(EamAttention eamAttention) {
        MessageUtil.checkEmpty(eamAttention, "eamAttention");
        //MessageUtil.checkEmpty(eamAttention.getAttentionBuild(), "attentionBuild");
        MessageUtil.checkEmpty(eamAttention.getAttentionType(), "attentionType");
        MessageUtil.checkEmpty(eamAttention.getUserId(), USERID);
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        //builder.must(QueryBuilders.termQuery("attentionBuild", eamAttention.getAttentionBuild()));
        builder.must(QueryBuilders.termQuery("attentionType", eamAttention.getAttentionType()));
        builder.must(QueryBuilders.termQuery(USERID, eamAttention.getUserId()));
        long totalNum = iamsEsAttentionDao.countByCondition(builder);
        Page<EamAttention> listByQuery = iamsEsAttentionDao.getListByQuery(1, (int) totalNum, builder);
        return listByQuery.getData();
    }

    @Override
    public List<CiDirVo> findMineAttentionSysList(Long userId) {
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        //builder.must(QueryBuilders.termQuery("attentionBuild", 2));
        builder.must(QueryBuilders.termQuery("attentionType", 1));
        builder.must(QueryBuilders.termQuery(USERID, userId));
        long totalNum = iamsEsAttentionDao.countByCondition(builder);
        Page<EamAttention> listByQuery = iamsEsAttentionDao.getListByQuery(1, (int) totalNum, builder);
        List<EamAttention> data = listByQuery.getData();
        List<CiDirVo> ciDirVoList = new ArrayList<>();
        for(EamAttention eamAttention : data) {
            EamCategory diagramDir = categorySvc.getById(eamAttention.getAttentionId(), LibType.DESIGN);
            if (diagramDir == null || diagramDir.getCiCode() == null) {
                continue;
            }
            ESCISearchBean bean = new ESCISearchBean();
            CCcCi cdt = new CCcCi();
            cdt.setCiCode(diagramDir.getCiCode());
            bean.setCdt(cdt);
            CiGroupPage ciGroupPage = iciApiSvc.queryPageBySearchBean(bean, false);
            List<CcCiInfo> ciInfo = ciGroupPage.getData();
            Map<String, String> attrs = ciInfo.get(0).getAttrs();

            CCcCiClass cCcCiClass = new CCcCiClass();
            cCcCiClass.setId(ciInfo.get(0).getCi().getClassId());
            List<CcCiClassInfo> ccCiClassList = iciClassApiSvc.queryClassByCdt(cCcCiClass);
            String className = ccCiClassList.get(0).getCiClass().getClassName();

            if (Env.APP_SUBSYSTEM.getClassName().equals(className)) {
                String contact = attrs.get("业务联系人及部门");
                if (!StringUtils.isEmpty(contact) && contact.startsWith("[") && contact.endsWith("]")) {
                    List<String> list = (List) JSONObject.parseArray(contact);
                    StringJoiner stringJoiner = new StringJoiner(", ");
                    list.forEach(stringJoiner::add);
                    contact = stringJoiner.toString();
                }
                CiDirVo ciDirVo = new CiDirVo();
                ciDirVo.setSystemName(attrs.get("子系统名称"));
                ciDirVo.setSystemSign(attrs.get("子系统标识"));
                ciDirVo.setSystemType(attrs.get("子系统分类"));
                ciDirVo.setLevel(attrs.get("重要性等级"));
                ciDirVo.setProductStatus(attrs.get("投产状态"));
                ciDirVo.setBelongDepart(attrs.get("归属处室"));
                ciDirVo.setLeader(attrs.get("子系统负责人"));
                ciDirVo.setContacts(contact);
                ciDirVoList.add(ciDirVo);
            } else if ( Env.APP.getClassName().equals(className)) {
                CiDirVo ciDirVo = new CiDirVo();
                ciDirVo.setSystemName(attrs.get("应用系统中文名称"));
                ciDirVo.setSystemSign(attrs.get("应用系统编号"));
                ciDirVo.setSystemType(attrs.get("应用系统分类"));
                ciDirVo.setLevel(attrs.get("重要性等级"));
                ciDirVo.setProductStatus(attrs.get("所属业务能力"));
                ciDirVo.setBelongDepart(attrs.get("所属层级"));
                ciDirVo.setLeader(attrs.get("管理员"));
                ciDirVo.setContacts(attrs.get("所属应用域"));
                ciDirVo.setRemark(attrs.get("应用系统简介"));
                ciDirVoList.add(ciDirVo);
            }
        }
        return ciDirVoList;
    }

    @Override
    public Long countAttentionNum(AttentionDto attentionDto) {
        MessageUtil.checkEmpty(attentionDto, "attentionDto");
        //MessageUtil.checkEmpty(attentionDto.getAttentionBuild(), "attentionBuild");
        MessageUtil.checkEmpty(attentionDto.getUserId(), USERID);
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        //builder.must(QueryBuilders.termQuery("attentionBuild", attentionDto.getAttentionBuild()));
        builder.must(QueryBuilders.termQuery(USERID, attentionDto.getUserId()));
        return iamsEsAttentionDao.countByCondition(builder);
    }

    @Override
    public EamAttention getEamAttention(Integer attentionBuild, Long attentionId, Long userId) {
        MessageUtil.checkEmpty(attentionId, "attentionId");
        MessageUtil.checkEmpty(userId, USERID);
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
//        if (attentionBuild != null) {
//            builder.must(QueryBuilders.termQuery("attentionBuild", attentionBuild));
//        }
        builder.must(QueryBuilders.termQuery("attentionId", attentionId));
        builder.must(QueryBuilders.termQuery(USERID, userId));
        List<EamAttention> listByQuery = iamsEsAttentionDao.getListByQuery(builder);
        if (!CollectionUtils.isEmpty(listByQuery)) {
            return listByQuery.get(0);
        }
        return null;
    }

    @Override
    public EamAttention getEamAttentionByType(Integer attentionType, Long attentionId, Long userId, String attentionCode, Integer source) {
        MessageUtil.checkEmpty(attentionId, "attentionId");
        MessageUtil.checkEmpty(userId, USERID);
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        if (attentionType == 4) {
            builder.must(QueryBuilders.termQuery("attentionCode.keyword", attentionCode));
            builder.must(QueryBuilders.termQuery("source", source));

        } else {
            builder.must(QueryBuilders.termQuery("attentionId", attentionId));
        }
        builder.must(QueryBuilders.termQuery(USERID, userId));
        builder.must(QueryBuilders.termQuery("attentionType", attentionType));
        List<EamAttention> listByQuery = iamsEsAttentionDao.getListByQuery(builder);
        if (!CollectionUtils.isEmpty(listByQuery)) {
            return listByQuery.get(0);
        }
        return null;
    }

    @Override
    public List<Long> getMyAttentionPlans() {
        CEamAttention cEamAttention = new CEamAttention();
        cEamAttention.setUserId(SysUtil.getCurrentUserInfo().getId());
        cEamAttention.setAttentionType(3);
        List<EamAttention> list = iamsEsAttentionDao.getListByCdt(cEamAttention);
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        return list.stream().map(EamAttention::getAttentionId).collect(Collectors.toList());
    }


    @Override
    public AttentionVo getMineFocus(int pageNum, int pageSize, AttentionDto attentionDto) {
        // 封装查询条件
        BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
        queryBuilder.must(QueryBuilders.termQuery(USERID, attentionDto.getUserId()));
        AttentionVo attentionVo = new AttentionVo();
        // 视图列表
        List<ESDiagram> diagramList = new ArrayList<>();
        // 获取分页数据
        List<SortBuilder<?>> sorts = new ArrayList<>();
        sorts.add(SortBuilders.fieldSort(MODIFY_TIME).order(SortOrder.DESC));
        Page<EamAttention> eamAttentionPage = iamsEsAttentionDao.getSortListByQuery(pageNum, pageSize, queryBuilder, sorts);
        if(CollectionUtils.isEmpty(eamAttentionPage.getData())){
            attentionVo.setDiagramList(diagramList);
            return attentionVo;
        }
        List<EamAttention> data = eamAttentionPage.getData();
        List<EamAttention> attentionDiagrams = data.stream()
                .filter(att -> att.getAttentionType() != null
                        && att.getAttentionType() == 2).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(attentionDiagrams)) {
            List<Long> attentionDiagramIds = attentionDiagrams.stream().map(EamAttention::getAttentionId).distinct().collect(Collectors.toList());
            List<ESDiagram> attentionDiagramList = diagramApiClient.getByIds(attentionDiagramIds, null, Lists.newArrayList(1, 0));
            Map<Long, ESDiagram> diagramMap = attentionDiagramList.stream().collect(Collectors.toMap(ESDiagram::getId, each -> each, (k1, k2) -> k2));
            for(EamAttention attention : attentionDiagrams) {
                ESDiagram diagram = diagramMap.get(attention.getAttentionId());
                if (BinaryUtils.isEmpty(diagram)) {
                    iamsEsAttentionDao.deleteById(attention.getId());
                    continue;
                }
                if (!StringUtils.isEmpty(attentionDto.getLike()) && !diagram.getName().contains(attentionDto.getLike())) {
                    continue;
                }
                diagram.setIsAttention(DiagramConstant.IS_ATTENTION);
                diagramList.add(diagram);
            }
            attentionVo.setDiagramList(diagramList);
        }
        // 封装分页信息
        Map<String, Long> pageMap = this.transResult(pageNum, pageSize, eamAttentionPage);
        attentionVo.setPageMap(pageMap);
        attentionVo.setAttentionList(data);
        return attentionVo;
    }

    private Map<String, Long> transResult(Integer pageNum, Integer pageSize, Page<EamAttention> eamAttentionPage) {
        Map<String, Long> pageMap = new HashMap<>();
        pageMap.put("pageNum", pageNum.longValue());
        pageMap.put("pageSize", pageSize.longValue());
        pageMap.put("totalPages", eamAttentionPage.getTotalPages());
        pageMap.put("totalRows", eamAttentionPage.getTotalRows());
        return pageMap;
    }

    @Override
    public List<Long> getMyAttentionDiagramIds() {
        CEamAttention cEamAttention = new CEamAttention();
        cEamAttention.setUserId(SysUtil.getCurrentUserInfo().getId());
        cEamAttention.setAttentionType(2);
        List<EamAttention> list = iamsEsAttentionDao.getListByCdt(cEamAttention);
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        return list.stream().map(EamAttention::getAttentionId).collect(Collectors.toList());
    }

    @Override
    public List<EamAttention> findCurrentUserAttentionList() {
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        builder.must(QueryBuilders.termQuery(USERID, SysUtil.getCurrentUserInfo().getId()));
        long totalNum = iamsEsAttentionDao.countByCondition(builder);
        Page<EamAttention> listByQuery = iamsEsAttentionDao.getListByQuery(1, (int) totalNum, builder);
        return listByQuery.getData();
    }

    @Override
    public Integer batchCancelAttention(CEamAttention eamAttention) {
        MessageUtil.checkEmpty(eamAttention, "eamAttention");
        MessageUtil.checkEmpty(eamAttention.getAttentionBuild(), "attentionBuild");
        MessageUtil.checkEmpty(eamAttention.getAttentionType(), "attentionType");
        if (eamAttention.getAttentionId() == null && CollectionUtils.isEmpty(eamAttention.getAttentionIds())) {
            throw new BusinessException("关注类型不能为空!");
        }
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        if (eamAttention.getAttentionId() != null) {
            builder.must(QueryBuilders.termQuery("attentionId", eamAttention.getAttentionId()));
        }
        if (!CollectionUtils.isEmpty(eamAttention.getAttentionIds())) {
            builder.must(QueryBuilders.termsQuery("attentionId", eamAttention.getAttentionIds()));
        }
        builder.must(QueryBuilders.termQuery("attentionBuild", eamAttention.getAttentionBuild()));
        builder.must(QueryBuilders.termQuery("attentionType", eamAttention.getAttentionType()));
        if (eamAttention.getUserId() != null) {
            builder.must(QueryBuilders.termQuery(USERID, eamAttention.getUserId()));
        }
        return iamsEsAttentionDao.deleteByQuery(builder, true);
    }
}
